/**
 * 
 */
package com.autoscript.ui.template.function;

import java.util.List;

import com.autoscript.ui.helper.StringHelper;
import com.autoscript.ui.helper.TypeConversionHelper;
import com.autoscript.ui.helper.UIPropertyHelper;

import freemarker.template.TemplateMethodModel;
import freemarker.template.TemplateModelException;

/**
 * @author Administrator
 * 字符串插入
 */
public class StringInsert implements TemplateMethodModel {

	@Override
	public Object exec(List args) throws TemplateModelException {
		//格式: StringInsert(字符串,插入字符串,插入位置)
		if(args.size()!=3 ){
			throw new TemplateModelException(UIPropertyHelper.getString("exception.func_para_number_not_match","StringInsert",args.size(),"3"));
		}
		String strMonther;
		strMonther = (String) args.get(0);
		String strInsert;
		strInsert = (String) args.get(1);
		String strInsertPos;
		strInsertPos = (String) args.get(2);
		//去掉逗号
		strInsertPos = StringHelper.replaceAllIgnoreCase(strInsertPos, ",", "");
		int insertPos;
		try {
			insertPos = TypeConversionHelper.StringToInt(strInsertPos.trim());
		} catch (Exception e) {
			e.printStackTrace();
			throw new TemplateModelException(UIPropertyHelper.getString("exception.invalidateFuncParamType","StringInsert",3,"数字","字符串"));
		}
		//如果insertPos大于strMonther长度报错
		if(insertPos>strMonther.length()-1) 
			throw new TemplateModelException(UIPropertyHelper.getString("exception.subscript_out_of_range", insertPos,strMonther.length()));
		StringBuilder temp = new StringBuilder();
		
		temp.append(strMonther.substring(0, insertPos)).append(strInsert)
		.append(strMonther.substring(insertPos));
		return temp.toString();
	}

}
